Introduction to Open Data Science - Course Project

About the Course

I heard about the course from an email send by Prof. Kimmo, himself, and decided to join. So thanks Kimmo. I am so excited to learn about all things Data Science.

Expect to learn

I have used R and Rstudio for about three years now. However, I have not yet tried out GitHub. I thought this would be a good chance and refresh my analytics skills.

A curious question

As I am a regular R user, I guess things like

  • Import and read data
  • Data visualization
  • Run linear models
  • Explore data

Would be familiar. I was wondering if, during the course, we will also explore writing R packages.


Regression and model validation

This chapter focuses on performing and interpreting regression analysis.

Read the students2014 data

The data is from an international survey of Approaches to Learning, made possible by Teachers’ Academy funding for KV in 2013-2015. The data has been filtered to include the desirable variables for analysis. The original data and variables descriptions can be found here.

data_analysis <- read.csv("learning2014.csv") # Read data from my local folder
str(data_analysis) # The data structure is data frame.
## 'data.frame':    166 obs. of  7 variables:
##  $ gender  : chr  "F" "M" "F" "M" ...
##  $ Age     : int  53 55 49 53 49 38 50 37 37 42 ...
##  $ attitude: num  3.7 3.1 2.5 3.5 3.7 3.8 3.5 2.9 3.8 2.1 ...
##  $ deep    : num  3.58 2.92 3.5 3.5 3.67 ...
##  $ stra    : num  3.38 2.75 3.62 3.12 3.62 ...
##  $ surf    : num  2.58 3.17 2.25 2.25 2.83 ...
##  $ Points  : int  25 12 24 10 22 21 21 31 24 26 ...
dim(data_analysis) # The data contains 166 observations or rows and 7 variables or columns.
## [1] 166   7
head(data_analysis, n = 3) # Three first rows
##   gender Age attitude     deep  stra     surf Points
## 1      F  53      3.7 3.583333 3.375 2.583333     25
## 2      M  55      3.1 2.916667 2.750 3.166667     12
## 3      F  49      2.5 3.500000 3.625 2.250000     24
tail(data_analysis, n = 3) # Three last rows
##     gender Age attitude     deep  stra     surf Points
## 164      F  18      3.7 3.166667 2.625 3.416667     18
## 165      F  19      3.6 3.416667 2.625 3.000000     30
## 166      M  21      1.8 4.083333 3.375 2.666667     19
  • The attitude column is a summary of the Attitude column, which is a sum of 10 questions related to students attitude towards statistics, each measured on the scale (1-5).
  • The “deep” column summarizes the “D” measures. Precisely, D03, D11, D19, D27, D07, D14, D22, D30,D06, D15, D23, D31.
  • The “surf” column summarizes the “SU” measures. Precisely, SU02, SU10, SU18, SU26, SU05, SU13, SU21, SU29, SU08, SU16, SU24, SU32.
  • The “stra” column summarizes the “ST” measures. Precisely, ST01, ST09, ST17, ST25, ST04, ST12, ST20, ST28.

A graphical overview of the data and summary of the variables

library(GGally) # Access the GGally library
library(ggplot2) # Access the ggplot2 library
# create plot matrix with ggpairs() by gender.
ggpairs(data_analysis, mapping = aes(col = gender, alpha = 0.3), lower = list(combo = wrap("facethist", bins = 20)))    

Interpretations:

  • There seem to be more females students than males, as it is shown form the gender bar plot.
  • The median age of males students is a little higher than females. On the other hand, the median point is somehow the same for males and females.
  • The “attitude” variable is positively correlated with the “Points” variable for both females and males. Same observation with the “stra” variable.
  • The rest of the variables are negatively correlated with the “Points” variable.
  • The “Age” variable is left-skewed. The other variables look somehow normal distributed with more than one mode.
summary(data_analysis) #  summary of the variables
##     gender               Age           attitude          deep      
##  Length:166         Min.   :17.00   Min.   :1.400   Min.   :1.583  
##  Class :character   1st Qu.:21.00   1st Qu.:2.600   1st Qu.:3.333  
##  Mode  :character   Median :22.00   Median :3.200   Median :3.667  
##                     Mean   :25.51   Mean   :3.143   Mean   :3.680  
##                     3rd Qu.:27.00   3rd Qu.:3.700   3rd Qu.:4.083  
##                     Max.   :55.00   Max.   :5.000   Max.   :4.917  
##       stra            surf           Points     
##  Min.   :1.250   Min.   :1.583   Min.   : 7.00  
##  1st Qu.:2.625   1st Qu.:2.417   1st Qu.:19.00  
##  Median :3.188   Median :2.833   Median :23.00  
##  Mean   :3.121   Mean   :2.787   Mean   :22.72  
##  3rd Qu.:3.625   3rd Qu.:3.167   3rd Qu.:27.75  
##  Max.   :5.000   Max.   :4.333   Max.   :33.00

Interpretations:

  • The students’ average age is 25 years, the youngest student is 17 years, while the oldest is 55 years.
  • The average exam point is 22.72, the lowest point is 7, while the highest point is 33.
  • The global attitude toward statistics, on average, is about 3.143 over 5.

Fit a regression model

For the regression model, the three chosen explanatory variables are attitude, stra, and surf. Their choice is based on the correlation analysis conducted on the step above. As it can be observed, the three variables are correlated with the response variable Points.

# Fit a multiple linear regression model using the lm() function
model1 <- lm(Points ~ attitude + stra + surf,
             data = data_analysis)
# Summary of the fitted model
summary(model1)
## 
## Call:
## lm(formula = Points ~ attitude + stra + surf, data = data_analysis)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -17.1550  -3.4346   0.5156   3.6401  10.8952 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept)  11.0171     3.6837   2.991  0.00322 ** 
## attitude      3.3952     0.5741   5.913 1.93e-08 ***
## stra          0.8531     0.5416   1.575  0.11716    
## surf         -0.5861     0.8014  -0.731  0.46563    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 5.296 on 162 degrees of freedom
## Multiple R-squared:  0.2074, Adjusted R-squared:  0.1927 
## F-statistic: 14.13 on 3 and 162 DF,  p-value: 3.156e-08

Interpretations: Both stra and surf variables are not statistically significant as their p-values are higher than 0.05 at 5% level of significance; the usually used significance level. Let us remove the variables one by one, starting from surf, and refit the model.

# Fit a new multiple linear regression model without the surf variable
model2 <- lm(Points ~ attitude + stra,
             data = data_analysis)
# Summary of the new fitted model
summary(model2)
## 
## Call:
## lm(formula = Points ~ attitude + stra, data = data_analysis)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -17.6436  -3.3113   0.5575   3.7928  10.9295 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept)   8.9729     2.3959   3.745  0.00025 ***
## attitude      3.4658     0.5652   6.132 6.31e-09 ***
## stra          0.9137     0.5345   1.709  0.08927 .  
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 5.289 on 163 degrees of freedom
## Multiple R-squared:  0.2048, Adjusted R-squared:  0.1951 
## F-statistic: 20.99 on 2 and 163 DF,  p-value: 7.734e-09

Interpretations: In the new fitted model, the remaining variables seem to be statistically significant, at least up to 10% level of significance for the stra variable.

Summary and model interpretations

In linear regression, the model interpretation depends on the used functional form. In this case, the used functional form is the linear-linear one, which means there was no log-transformation of the data.

Therefore, the interpretation goes as follows "One unit increase in x[explanatory variable] results in Beta_1 (the estimated parameter) unit increase in y[response variable]. Additionally, as the case is a multiple linear regression, for the interpretation, one must hold other factors fixed and interpret one variable at a time.

Interpretations:

  • By holding other factors fixed, an increase of one unit in the global attitude toward statistics results in 3.47 unit increase in the exam points.
  • By holding other factors fixed, an increase of one unit in stra results in 0.91 unit increase in the exam points. Recall that stra variable is a summary of different measures.

The R-squared is used to quantify how well the model fits the data. In simple linear regression, it is the quotient between the Sum Squared Explained (SSE) over Sum Squared Total (SST). The reason why, in multiple linear regression, it is recommended to assess the model fitting using the adjusted R squared, which take into accounts the number of the fitted parameters.

Interpretation: In the case of model2, Adjusted R squared = 0.1951, reflecting that the model explained 19.5% of the data. The higher the Adjusted R-squared, the better the model.

Diagnostic plots

# Plot the diagnostics plots: Residuals vs Fitted values, Normal QQ-plot and Residuals vs Leverage
par(mfrow = c(2,2)) # Divide the window into a 2-by-2 sub-windows. 
plot(model2, which = c(1,2,5))

  • The Q-Q plot: The plot is used to diagnose the normality assumption of the linear regression model. If most of the points lay on the line, it indicates that the assumption is justified.

Interpretation: most of the residuals points seem to lay on the line; the normality assumption is justified.

  • The Residuals vs Fitted values plot: The plot is used to quantify a the constant variance assumption. There has to be no pattern in the plot, which indicates that the size of the errors should not depend on the explanatory variables.

Interpretation: The residuals seem to be randomly distributed with respect to the fitted values; no pattern is observed; the assumption is justified.

  • The Residuals vs Leverage plot: The plot is used to investigate whether there is an outlier observation which can influence the outcome of the model.

Interpretation: No stand-up outlier is observed.


Logistic regression

This chapter focuses on performing and interpreting logistic regression analysis.

Read the joined student alcohol consumption data

The data are from two identical questionnaires related to secondary school student alcohol consumption in Portugal. Data source: UCI Machine Learning Repository. Metadata available here.

data_joined <- read.csv("pormath.csv") # Read data from my local folder
str(data_joined) # The data structure is data frame.
## 'data.frame':    370 obs. of  35 variables:
##  $ school    : chr  "GP" "GP" "GP" "GP" ...
##  $ sex       : chr  "F" "F" "F" "F" ...
##  $ age       : int  15 15 15 15 15 15 15 15 15 15 ...
##  $ address   : chr  "R" "R" "R" "R" ...
##  $ famsize   : chr  "GT3" "GT3" "GT3" "GT3" ...
##  $ Pstatus   : chr  "T" "T" "T" "T" ...
##  $ Medu      : int  1 1 2 2 3 3 3 2 3 3 ...
##  $ Fedu      : int  1 1 2 4 3 4 4 2 1 3 ...
##  $ Mjob      : chr  "at_home" "other" "at_home" "services" ...
##  $ Fjob      : chr  "other" "other" "other" "health" ...
##  $ reason    : chr  "home" "reputation" "reputation" "course" ...
##  $ nursery   : chr  "yes" "no" "yes" "yes" ...
##  $ internet  : chr  "yes" "yes" "no" "yes" ...
##  $ alc_use   : num  1 3 1 1 2.5 1 2 2 2.5 1 ...
##  $ high_use  : logi  FALSE TRUE FALSE FALSE TRUE FALSE ...
##  $ guardian  : chr  "mother" "mother" "mother" "mother" ...
##  $ traveltime: int  2 1 1 1 2 1 2 2 2 1 ...
##  $ studytime : int  4 2 1 3 3 3 3 2 4 4 ...
##  $ schoolsup : chr  "yes" "yes" "yes" "yes" ...
##  $ famsup    : chr  "yes" "yes" "yes" "yes" ...
##  $ activities: chr  "yes" "no" "yes" "yes" ...
##  $ higher    : chr  "yes" "yes" "yes" "yes" ...
##  $ romantic  : chr  "no" "yes" "no" "no" ...
##  $ famrel    : int  3 3 4 4 4 4 4 4 4 4 ...
##  $ freetime  : int  1 3 3 3 2 3 2 1 4 3 ...
##  $ health    : int  1 5 2 5 3 5 5 4 3 4 ...
##  $ goout     : int  2 4 1 2 1 2 2 3 2 3 ...
##  $ Walc      : int  1 4 1 1 3 1 2 3 3 1 ...
##  $ Dalc      : int  1 2 1 1 2 1 2 1 2 1 ...
##  $ failures  : int  0 1 0 0 1 0 1 0 0 0 ...
##  $ paid      : chr  "yes" "no" "no" "no" ...
##  $ absences  : int  3 2 8 2 5 2 0 1 9 10 ...
##  $ G1        : int  10 10 14 10 12 12 11 10 16 10 ...
##  $ G2        : int  12 8 13 10 12 12 6 10 16 10 ...
##  $ G3        : int  12 8 12 9 12 12 6 10 16 10 ...
dim(data_joined) # The data contains 370 observations or rows and 35 variables or columns.
## [1] 370  35
colnames(data_joined) # variables names
##  [1] "school"     "sex"        "age"        "address"    "famsize"   
##  [6] "Pstatus"    "Medu"       "Fedu"       "Mjob"       "Fjob"      
## [11] "reason"     "nursery"    "internet"   "alc_use"    "high_use"  
## [16] "guardian"   "traveltime" "studytime"  "schoolsup"  "famsup"    
## [21] "activities" "higher"     "romantic"   "famrel"     "freetime"  
## [26] "health"     "goout"      "Walc"       "Dalc"       "failures"  
## [31] "paid"       "absences"   "G1"         "G2"         "G3"

Four interesting variables in the data

The chosen variables are: Student grades(G3), sex, absences, and failures.

The hypotheses are:

  • H1: A higher alcohol use is associated with lower grades.
  • H2: A higher alcohol use is associated with sex.
  • H3: A higher alcohol use is associated with student absences.
  • H4: A higher alcohol use is associated with student failures.

Explore the distributions of the chosen variables

Student grades(G3) and Sex relationships with alcohol consumption

library(dplyr) # Access the dpyr library
library(ggplot2) # Access the ggplot2 library
data_joined %>%   # produce summary statistics by group
  group_by(sex, high_use) %>%
  summarise(count = n(), mean_grade = mean(G3))
## # A tibble: 4 x 4
## # Groups:   sex [2]
##   sex   high_use count mean_grade
##   <chr> <lgl>    <int>      <dbl>
## 1 F     FALSE      154       11.4
## 2 F     TRUE        41       11.8
## 3 M     FALSE      105       12.3
## 4 M     TRUE        70       10.3
ggplot(data_joined, aes(x = high_use, y = G3, col = sex)) + geom_boxplot() + ylab("grade") + ggtitle("Student grades by alcohol consumption and sex")

Comments:

  • 41 females students over 195 (i.e. 21%) are higher alcohol users.
  • 70 males students over 175 (i.e. 40%) are higher alcohol users. With these two comments, one can argue that H2 is satisfied.
  • On average, males alcohol user tend to have lower grades (2 points less than non-alcohol users).
  • For females, grades point average is quite the same for alcohol and non-alcohol users.
  • Looking at the boxplot, the non-alcohol user students have high grades. Especially, males, their median grade point is higher than females.
  • Higher alcohol user students tend to have lower grades. One can argue that H1 is satisfied.
  • For higher alcohol users, females tend to have a high median grade point than males.

Student absences relationships with alcohol consumption

ggplot(data_joined, aes(x = high_use, y = absences, col = sex)) + geom_boxplot() + ggtitle("Student absences by alcohol consumption and sex")

Comments:

  • High alcohol user students are more absent than non-alcohol users (H3 satisfied). And, the number of males students absent in this category is slightly higher than females.
  • For non-alcohol user students, females are more absent than males. However, their medium absent days are quite the same, for males and females.

Student failures relationships with alcohol consumption

ggplot(data_joined, aes(failures, fill = high_use)) + geom_bar(position = "dodge") + ggtitle("Student failures by alcohol consumption")

Comments:

  • For students who failed, got “0”, the counted number seems to be high for non-alcohol user. This comment suggests that H4 is not satisfied.
  • For those students who got “1” and “2”, the counted number seems to be the same for higher alcohol user and non-alcohol user.
  • For those students who got “3”, a slightly higher counted number seems to be higher alcohol user; again, suggesting that H4 is not satisfied.

Logistic regression analysis

This analysis explores the relationship between the four chosen variables and the binary high/low alcohol consumption variable as the target variable.

# Fit a logistic regression model using the glm() function
glm_model1 <- glm(high_use ~ G3 + failures + absences + sex, data = data_joined, family = "binomial")
# Summary of the fitted model
summary(glm_model1)
## 
## Call:
## glm(formula = high_use ~ G3 + failures + absences + sex, family = "binomial", 
##     data = data_joined)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -2.1561  -0.8429  -0.5872   1.0033   2.1393  
## 
## Coefficients:
##             Estimate Std. Error z value Pr(>|z|)    
## (Intercept) -1.38733    0.51617  -2.688  0.00719 ** 
## G3          -0.04671    0.03948  -1.183  0.23671    
## failures     0.50382    0.22018   2.288  0.02213 *  
## absences     0.09058    0.02322   3.901 9.56e-05 ***
## sexM         1.00870    0.24798   4.068 4.75e-05 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 452.04  on 369  degrees of freedom
## Residual deviance: 405.59  on 365  degrees of freedom
## AIC: 415.59
## 
## Number of Fisher Scoring iterations: 4
# Coefficients of the model
coef(glm_model1)
## (Intercept)          G3    failures    absences        sexM 
## -1.38732604 -0.04670941  0.50382370  0.09057516  1.00870144

Interpretations:

  • The student grades (G3) variable is not statistically significant; thus, it will be removed from the model. Hence, H1 is not satisfied
  • As the sex variables is a factor variable, the “female” part of the variable is the baseline, and its coefficient is simply the intercept.
  • The true coefficient of the “male” student would be -1.38733 + 1.00870 = -0.37863.

Let us fit the model without G3 variable and an intercept to see all coefficients directly.

# Fit a new logistic regression model 
glm_model2 <- glm(high_use ~ failures + absences + sex - 1, data = data_joined, family = "binomial")
# Summary of the fitted model
summary(glm_model2)
## 
## Call:
## glm(formula = high_use ~ failures + absences + sex - 1, family = "binomial", 
##     data = data_joined)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -2.1550  -0.8430  -0.5889   1.0328   2.0374  
## 
## Coefficients:
##          Estimate Std. Error z value Pr(>|z|)    
## failures  0.59759    0.20698   2.887  0.00389 ** 
## absences  0.09245    0.02323   3.979 6.91e-05 ***
## sexF     -1.94150    0.23129  -8.394  < 2e-16 ***
## sexM     -0.94418    0.19305  -4.891 1.00e-06 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 512.93  on 370  degrees of freedom
## Residual deviance: 406.99  on 366  degrees of freedom
## AIC: 414.99
## 
## Number of Fisher Scoring iterations: 4
# Coefficients of the model
coef(glm_model2)
##    failures    absences        sexF        sexM 
##  0.59759293  0.09245138 -1.94149584 -0.94418265
# compute odds ratios (OR)
OR <- coef(glm_model2) %>% exp

# compute confidence intervals (CI)
CI <- confint(glm_model2) %>% exp

# print out the odds ratios with their confidence intervals
cbind(OR, CI)
##                 OR      2.5 %    97.5 %
## failures 1.8177381 1.21997630 2.7642305
## absences 1.0968598 1.05041937 1.1508026
## sexF     0.1434892 0.08940913 0.2219242
## sexM     0.3889974 0.26411123 0.5638009

Interpretations:

  • All coefficients are statistically significant. All variables are highly significant predictors of the probability of high alcohol consumption in students.
  • Also, the model accuracy has improved. In terms of Information criteria, the model1 had an AIC = 415.59, while model2 has an AIC = 414.99; thus, model2 is the preferable one.
  • The odds of failures for a higher user alcohol students is estimated to 1.817 be with 95 CI of [1.219, 2.764]. Note: The interval contains 1, i.e the increase in the odds of being a higher alcohol user student associated with a 1 unit increase failures is estimated to be between 21% and 170%.
  • The odds of absences for a higher user alcohol students is estimated to 1.096 be with 95 CI of [1.050, 1.150]. Note: The interval contains 1, i.e the increase in the odds of being a higher alcohol user student associated with a 1 unit increase absences is estimated to be between 5% and 15%.
  • The odd of a male student being a higher alcohol user is estimated to be 0.388 with 95 CI of [0.264, 0.563]. i.e it is between 26% and 56% of the corresponding odds for a female student.
  • The odd of a female student being a higher alcohol user is estimated to be 0.143 with 95 CI of [0.089, 0.221]. i.e it is between 8% and 22% of the corresponding odds for a female student.

Explore the predictive power of the model

# predict() the probability of high_use
probabilities <- predict(glm_model2, type = "response")

# add the predicted probabilities to 'data_joined'
data_joined <- mutate(data_joined, probability = probabilities)

# use the probabilities to make a prediction of high_use
data_joined <- mutate(data_joined, prediction = probability > 0.5)

# see the first ten original classes, predicted probabilities, and class predictions
select(data_joined, failures, absences, sex, high_use, probability, prediction) %>% head(10)
##    failures absences sex high_use probability prediction
## 1         0        3   F    FALSE   0.1592068      FALSE
## 2         1        2   F     TRUE   0.2388490      FALSE
## 3         0        8   F    FALSE   0.2311401      FALSE
## 4         0        2   F    FALSE   0.1472175      FALSE
## 5         1        5   F     TRUE   0.2928368      FALSE
## 6         0        2   F    FALSE   0.1472175      FALSE
## 7         1        0   F    FALSE   0.2068690      FALSE
## 8         0        1   F    FALSE   0.1359851      FALSE
## 9         0        9   F     TRUE   0.2479765      FALSE
## 10        0       10   F    FALSE   0.2656157      FALSE
# tabulate the target variable versus the predictions
table(high_use = data_joined$high_use, 
       prediction = data_joined$prediction)
##         prediction
## high_use FALSE TRUE
##    FALSE   252    7
##    TRUE     78   33

Comments:

  • They are 252 true negatives and 33 true positives, i.e the model was able to explain 252 over 300 FALSEs, and 33 over 40 TRUEs.
  • 7 false negatives and 78 false positives, i.e the model missed 7 over 40 TRUEs and 78 over 300 FALSEs.

Let us check the accuracy and loss functions of the model

# define a loss function (mean prediction error)
loss_func <- function(class, prob) {
  n_wrong <- abs(class - prob) > 0.5
  mean(n_wrong)
}

# call loss_func to compute the average number of wrong predictions in the (training) data
loss_func(class = data_joined$high_use, prob = data_joined$probability)
## [1] 0.2297297

Comments: The mean of incorrectly classified observations can be thought of as a penalty (loss) function for the classifier. Less penalty = good. The aim is to minimize the incorrectly classified observations. Model2 has a mean prediction error of about 23%.

Bonus: Perform 10-fold cross-validation on the model

library(boot)
cv <- cv.glm(data = data_joined, cost = loss_func, glmfit = glm_model2, K = 10)

# average number of wrong predictions in the cross validation
cv$delta[1]
## [1] 0.2432432

Comments: Yes, model2 has a small prediction error (0.23 error) compared to the model introduced in DataCamp (0.26 error).


Clustering and classification

This chapter focuses on performing and interpreting clustering and classification on the Boston data set.

Load the Boston data set

The data are for the housing values in suburbs of Boston. The data are available from the MASS package and the variable descriptions can be found here.

library(MASS)
data("Boston") # load the data
str(Boston) # A data frame
## 'data.frame':    506 obs. of  14 variables:
##  $ crim   : num  0.00632 0.02731 0.02729 0.03237 0.06905 ...
##  $ zn     : num  18 0 0 0 0 0 12.5 12.5 12.5 12.5 ...
##  $ indus  : num  2.31 7.07 7.07 2.18 2.18 2.18 7.87 7.87 7.87 7.87 ...
##  $ chas   : int  0 0 0 0 0 0 0 0 0 0 ...
##  $ nox    : num  0.538 0.469 0.469 0.458 0.458 0.458 0.524 0.524 0.524 0.524 ...
##  $ rm     : num  6.58 6.42 7.18 7 7.15 ...
##  $ age    : num  65.2 78.9 61.1 45.8 54.2 58.7 66.6 96.1 100 85.9 ...
##  $ dis    : num  4.09 4.97 4.97 6.06 6.06 ...
##  $ rad    : int  1 2 2 3 3 3 5 5 5 5 ...
##  $ tax    : num  296 242 242 222 222 222 311 311 311 311 ...
##  $ ptratio: num  15.3 17.8 17.8 18.7 18.7 18.7 15.2 15.2 15.2 15.2 ...
##  $ black  : num  397 397 393 395 397 ...
##  $ lstat  : num  4.98 9.14 4.03 2.94 5.33 ...
##  $ medv   : num  24 21.6 34.7 33.4 36.2 28.7 22.9 27.1 16.5 18.9 ...
dim(Boston) 
## [1] 506  14

Comment: The data frame has 506 rows and 14 columns. All variables are numeric, with the variable chas: Charles River dummy variable (= 1 if tract bounds river; 0 otherwise).

A graphical overview of the data and summary of the variables

Matrix plot of the variables

# plot matrix of the variables
pairs(Boston,
      col = "blue", # Change color
      pch = 18,    # Change shape of points
      main = "Matrix plot of the variables") # Add a main title

The upper correlation matrix

library(corrplot) # access the corrplot library
# visualize the upper correlation matrix
corrplot(cor_matrix, method="circle", type = "upper")

Interpretations:

  • There seems to be a positive correlation between per capita crime rate by town (crim) and the index of accessibility to radial highways (rad) and also full-value property-tax rate per $10,000 (tax).

  • A slightly positive correlation between per capita crime rate by town (crim) with proportion of non-retail business acres per town (indus), nitrogen oxides concentration (parts per 10 million) (nox), and lower status of the population (percent) (lstat).

  • A positive correlation between the proportion of residential land zoned for lots over 25,000 square feet (zn) and the weighted mean of distances to five Boston employment centres (dis).

  • A positive correlation between the proportion of non-retail business acres per town (indus) with nitrogen oxides concentration (parts per 10 million) (nox), proportion of owner-occupied units built prior to 1940 (age), index of accessibility to radial highways (rad), full-value property-tax rate per $10,000 (tax), and lower status of the population (percent) (lstat).

  • A positive correlation between average number of rooms per dwelling (rm) with median value of owner-occupied homes in $1000s (medv).

  • A negative correlation between: lower status of the population (percent) (lstat) and median value of owner-occupied homes in $1000s (medv).

  • Moreover, three variables are negatively correlated with the weighted mean of distances to five Boston employment centres (dis). Those are proportion of owner-occupied units built prior to 1940 (age), nitrogen oxides concentration (parts per 10 million) (nox), and proportion of non-retail business acres per town (indus).

Summary of the variables

summary(Boston) 
##       crim                zn             indus            chas        
##  Min.   : 0.00632   Min.   :  0.00   Min.   : 0.46   Min.   :0.00000  
##  1st Qu.: 0.08205   1st Qu.:  0.00   1st Qu.: 5.19   1st Qu.:0.00000  
##  Median : 0.25651   Median :  0.00   Median : 9.69   Median :0.00000  
##  Mean   : 3.61352   Mean   : 11.36   Mean   :11.14   Mean   :0.06917  
##  3rd Qu.: 3.67708   3rd Qu.: 12.50   3rd Qu.:18.10   3rd Qu.:0.00000  
##  Max.   :88.97620   Max.   :100.00   Max.   :27.74   Max.   :1.00000  
##       nox               rm             age              dis        
##  Min.   :0.3850   Min.   :3.561   Min.   :  2.90   Min.   : 1.130  
##  1st Qu.:0.4490   1st Qu.:5.886   1st Qu.: 45.02   1st Qu.: 2.100  
##  Median :0.5380   Median :6.208   Median : 77.50   Median : 3.207  
##  Mean   :0.5547   Mean   :6.285   Mean   : 68.57   Mean   : 3.795  
##  3rd Qu.:0.6240   3rd Qu.:6.623   3rd Qu.: 94.08   3rd Qu.: 5.188  
##  Max.   :0.8710   Max.   :8.780   Max.   :100.00   Max.   :12.127  
##       rad              tax           ptratio          black       
##  Min.   : 1.000   Min.   :187.0   Min.   :12.60   Min.   :  0.32  
##  1st Qu.: 4.000   1st Qu.:279.0   1st Qu.:17.40   1st Qu.:375.38  
##  Median : 5.000   Median :330.0   Median :19.05   Median :391.44  
##  Mean   : 9.549   Mean   :408.2   Mean   :18.46   Mean   :356.67  
##  3rd Qu.:24.000   3rd Qu.:666.0   3rd Qu.:20.20   3rd Qu.:396.23  
##  Max.   :24.000   Max.   :711.0   Max.   :22.00   Max.   :396.90  
##      lstat            medv      
##  Min.   : 1.73   Min.   : 5.00  
##  1st Qu.: 6.95   1st Qu.:17.02  
##  Median :11.36   Median :21.20  
##  Mean   :12.65   Mean   :22.53  
##  3rd Qu.:16.95   3rd Qu.:25.00  
##  Max.   :37.97   Max.   :50.00

Interpretations: On average,

  • The per capital crime rate by the town is about 3.61.
  • The proportion of residential land zoned for lots over 25,000 square feet is about 11.36.
  • The proportion of non-retail business acres per town is about 11.14.
  • The nitrogen oxides concentration (parts per 10 million) is about 0.55.
  • The average number of rooms per dwelling is about 6.
  • The proportion of owner-occupied units built prior to 1940 is about 68.57.
  • The full-value property-tax rate per $10,000 is about 408.2.
  • The pupil-teacher ratio by town is about 18.46.
  • The median value of owner-occupied homes in $1000s is about 22.53.
  • The chas Charles River dummy variable (= 1 if tract bounds river; 0 otherwise). Its mean is about 0.069.

Standardize the dataset

# center and standardize variables
boston_scaled <- scale(Boston)

# change the object to data frame
boston_scaled <- as.data.frame(boston_scaled)

# summaries of the scaled variables
summary(boston_scaled)
##       crim                 zn               indus              chas        
##  Min.   :-0.419367   Min.   :-0.48724   Min.   :-1.5563   Min.   :-0.2723  
##  1st Qu.:-0.410563   1st Qu.:-0.48724   1st Qu.:-0.8668   1st Qu.:-0.2723  
##  Median :-0.390280   Median :-0.48724   Median :-0.2109   Median :-0.2723  
##  Mean   : 0.000000   Mean   : 0.00000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.007389   3rd Qu.: 0.04872   3rd Qu.: 1.0150   3rd Qu.:-0.2723  
##  Max.   : 9.924110   Max.   : 3.80047   Max.   : 2.4202   Max.   : 3.6648  
##       nox                rm               age               dis         
##  Min.   :-1.4644   Min.   :-3.8764   Min.   :-2.3331   Min.   :-1.2658  
##  1st Qu.:-0.9121   1st Qu.:-0.5681   1st Qu.:-0.8366   1st Qu.:-0.8049  
##  Median :-0.1441   Median :-0.1084   Median : 0.3171   Median :-0.2790  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.5981   3rd Qu.: 0.4823   3rd Qu.: 0.9059   3rd Qu.: 0.6617  
##  Max.   : 2.7296   Max.   : 3.5515   Max.   : 1.1164   Max.   : 3.9566  
##       rad               tax             ptratio            black        
##  Min.   :-0.9819   Min.   :-1.3127   Min.   :-2.7047   Min.   :-3.9033  
##  1st Qu.:-0.6373   1st Qu.:-0.7668   1st Qu.:-0.4876   1st Qu.: 0.2049  
##  Median :-0.5225   Median :-0.4642   Median : 0.2746   Median : 0.3808  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 1.6596   3rd Qu.: 1.5294   3rd Qu.: 0.8058   3rd Qu.: 0.4332  
##  Max.   : 1.6596   Max.   : 1.7964   Max.   : 1.6372   Max.   : 0.4406  
##      lstat              medv        
##  Min.   :-1.5296   Min.   :-1.9063  
##  1st Qu.:-0.7986   1st Qu.:-0.5989  
##  Median :-0.1811   Median :-0.1449  
##  Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.6024   3rd Qu.: 0.2683  
##  Max.   : 3.5453   Max.   : 2.9865

How did the variables change?: The variables have been rescaled to have a mean of zero and a standard deviation of one. For a standardized variable, each case’s value on the standardized variable indicates it’s difference from the mean of the original variable in number of standard deviations (of the original variable).

# Create a categorical variable of the crime rate

# create a quantile vector of crim and print it
bins <- quantile(boston_scaled$crim)

# create a categorical variable 'crime'
crime <- cut(boston_scaled$crim, breaks = bins, include.lowest = TRUE, label = c("low", "med_low", "med_high", "high"))

# look at the table of the new factor crime
table(crime)
## crime
##      low  med_low med_high     high 
##      127      126      126      127
# Drop the old crime rate variable from the dataset
boston_scaled <- dplyr::select(boston_scaled, -crim)

# add the new categorical value to scaled data
boston_scaled <- data.frame(boston_scaled, crime)

# Divide the dataset to train and test sets

# number of rows in the Boston dataset 
n <- nrow(boston_scaled)

# choose randomly 80% of the rows
ind <- sample(n,  size = n * 0.8)

# create train set
train <- boston_scaled[ind,]

# create test set 
test <- boston_scaled[-ind,]

# save the correct classes from test data
correct_classes <- test$crime

# remove the crime variable from test data
test <- dplyr::select(test, -crime)

Fit the linear discriminant analysis on the train set

# linear discriminant analysis
lda.fit <- lda(crime ~ ., data = train)

# the function for lda biplot arrows
lda.arrows <- function(x, myscale = 1, arrow_heads = 0.1, color = "red", tex = 0.75, choices = c(1,2)){
  heads <- coef(x)
  arrows(x0 = 0, y0 = 0, 
         x1 = myscale * heads[,choices[1]], 
         y1 = myscale * heads[,choices[2]], col=color, length = arrow_heads)
  text(myscale * heads[,choices], labels = row.names(heads), 
       cex = tex, col=color, pos=3)
}

# target classes as numeric
classes <- as.numeric(train$crime)

# plot the lda results
plot(lda.fit, dimen = 2, col = classes, pch = classes)
lda.arrows(lda.fit, myscale = 1.3)

Prediction of the classes with the LDA model on the test data

# Save the crime categories from the test set and then remove the categorical crime variable from the test dataset. DONE -- See above steps.

# predict classes with test data
lda.pred <- predict(lda.fit, newdata = test)

# cross tabulate the results
tbl_lda <- table(correct = correct_classes, predicted = lda.pred$class)
tbl_lda; rowSums(tbl_lda)
##           predicted
## correct    low med_low med_high high
##   low       16      11        0    0
##   med_low    7      19        3    0
##   med_high   0      11       18    0
##   high       0       0        0   17
##      low  med_low med_high     high 
##       27       29       29       17

Comments: From the table, we see that the LDA predicts correctly:

  • 16 out of 28 (i.e., 57.1%) low.
  • 21 out of 26 (i.e., 80.8%) med_low.
  • 18 out of 22 (i.e., 81.8%) med_high.
  • All 26 (i.e., 100%) high.

Reload the dataset, standardize and run k-means algorithm

data("Boston") # Reload
Re_data <- scale(Boston) # standardize it

# distances between the observations
dist_eu <- dist(Re_data)

# k-means clustering with 3 clusters
km <- kmeans(Re_data, centers = 3)

# investigate what is the optimal number of clusters 

set.seed(123) # set the seed

# determine the number of clusters
k_max <- 10

# calculate the total within sum of squares
twcss <- sapply(1:k_max, function(k){kmeans(Re_data, k)$tot.withinss})

# visualize the results
library(ggplot2)
qplot(x = 1:k_max, y = twcss, geom = 'line')

Comment: The “scree plot” above helps to identify the appropriate number of clusters. The “elbow shape” suggests that two clusters (k = 2) is the potential candidate, since the total WCSS drops radically.

# run the algorithm again

# k-means clustering
km_new <- kmeans(Re_data, centers = 2)

# plot the Re_scale Boston dataset with 2 clusters
pairs(Re_data, col = km_new$cluster)

table(km_new$cluster) 
## 
##   1   2 
## 329 177

Comment: With k = 2, clusters consist of 329 observations out of 506 in cluster 1, and cluster 2, 177 observations. The clusters are also separated by colour within the predictors. Some variables present a clear cut of observations, other it is a quite mix.

Bonus

model_predictors <- dplyr::select(train, -crime)
# check the dimensions
dim(model_predictors)
## [1] 404  13
dim(lda.fit$scaling)
## [1] 13  3
# matrix multiplication
matrix_product <- as.matrix(model_predictors) %*% lda.fit$scaling
matrix_product <- as.data.frame(matrix_product)

library(plotly) # access plotly library

# 3D plot of the columns of the matrix 
plot_ly(x = matrix_product$LD1, y = matrix_product$LD2, z = matrix_product$LD3, type= 'scatter3d', mode='markers', surfacecolor = train$crime)
# another 3D plot with color defined by the clusters of the k-means
plot_ly(x = matrix_product$LD1, y = matrix_product$LD2, z = matrix_product$LD3, type= 'scatter3d', mode='markers', surfacecolor = km_new$cluster)

How do the plots differ? Are there any similarities?: The two plots look relatively similar with a clear cut between clusters, and the number of observation within each group seems to be the same.